const app = getApp()
import webSocket from '../../utils/socket'
import fetch from '../../utils/services'
const {
  windowWidth,
  windowHeight
} = wx.getSystemInfoSync() 
Page({
  data: {
    message: '',
    list: [], // 文字聊天列表
    myInfo: {
    },
    userInfo: {
    },
    chatInfo: {
    },
    toView: '', // 文字表情聊天列表滚动到的位置
    isMetting: false, // 正在进行音视频
    isWaiting: false, // 正在等待接听音视频
    waitingType: '1', // 等待接听音视频的类型  1: 视频  2:音频,
    isScaled: false, // 是否缩小窗口
    cursorSpacing: 6,
    contactsCode: '', // 传过来的联系id
    hiddened: false // 是否已隐藏
  },
  onLoad: function (options) {
    console.log('视频会议参数：',options)
    wx.setNavigationBarTitle({
      title: '语会视频会议'
    })
    this.setData({
      chatInfo: app.globalData.chatInfo,
      isWaiting: options.isWaiting ? true : false,
      contactsCode: options.contactsCode,
      mettingType: app.globalData.chatInfo.type === '1' ? '2' : '1',
      waitingType: app.globalData.chatInfo.converseType === '1' ? '2' : '1'
    })
    const myInfo = {
      userId: app.globalData.myInfo.userCode,
      name: app.globalData.myInfo.userName,
      avator: app.globalData.myInfo.userPic,
      uid: app.globalData.myInfo.uid,
    }
    this.setData({
      myInfo,
      userInfo: app.globalData.userInfo
    })
    console.log('打印用户信息',app.globalData.userInfo)
    wx.onKeyboardHeightChange(res => {
      console.log(res.height)
    })
    if (true) {
      // 从网页跳转过来的，默认发一条消息体
      const param = {
        fromUserId: this.data.myInfo.userId,
        toUserId: this.data.userInfo.userId,
        type: 1,
        objectName: 'RC:TxtMsg',
        content: this.data.userInfo.name + '你好，我已准备好了，可以开始会议了'
      }
      const tipsParam = {
        fromUserId: this.data.myInfo.userId,
        toUserId: this.data.userInfo.userId,
        type: 1,
        objectName: 'RC:InfoNtf',
        content: '温馨提示：\n1. 对方正在使用小程序，可能会由于离开小程序而收不到消息提醒\n2. 若对方长时间未响应，请尝试用其他通讯方式提醒再次进入小程序'
      }
      webSocket.sendSocketMessage({
        data: JSON.stringify(param),
        success: res => {
          console.log(1, res)
        },
        fail: err => {
          console.log(err)
        }
      })
      webSocket.sendSocketMessage({
        data: JSON.stringify(tipsParam),
        success: res => {
          console.log(1, res)
        },
        fail: err => {
          console.log(err)
        }
      })
    }
  },
  onShow: function() {
    this.customSocket()
    if (this.data.hiddened) {
      wx.navigateBack()
    }
    this.setData ({
      hiddened: false
    })
  },
  
  onHide: function() {
    // 退回时为拒接
    if (this.data.isWaiting) {
      this.decline()
    }
    // 退回时为 挂断
    if (this.data.isMetting) {
      this.handup(true)
    }
    // app.socketAction()
    this.setData({
      hiddened: true
    })
  },
  onUnload: function() {
    // 退回时为拒接
    if (this.data.isWaiting) {
      this.decline()
    }
    // 退回时为 挂断
    if (this.data.isMetting) {
       this.handup(true)
    }
    app.socketAction()
  },

  // 主动开启连接
  startConnect: function() {
    let that = this
    wx.showActionSheet({
      itemList: ['语音通话','视频通话'],
      success (res) {
        console.log(res.tapIndex)
        if (res.tapIndex === 0) {
          that.startToTalk(1)
        } else if (res.tapIndex === 1) {
          that.startToTalk(2)
        }
      },
      fail (res) {
        console.log(res.errMsg)
      }
    })
  },

  startToTalk: function(converseType) {
    wx.showLoading({
      title: '正在加载...',
    })
    const param = {
      contactsCode: this.data.contactsCode,
      converseType: converseType
    }
    fetch.post('/converse/launchConverse', param).then(result => {
      wx.hideLoading()
      const chatInfo = {
        userId: this.data.userInfo.userId,
        avator: this.data.userInfo.avator,
        name: this.data.userInfo.name,
        contactsCode: this.data.contactsCode,
        converseCode: result.converseCode,
        converseType: result.converseType,
        resourceToken: result.resourceToken,
        type: '1',
      }
      console.log('发起通话参数' + JSON.stringify(this.data))
      this.setData({
        chatInfo,
        waitingType: result.converseType === 1 ? '2' : '1',
        isWaiting: false,
        isMetting: true
      })
      
    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: err.message,
        duration : 2000,
        icon: 'none',
      })
      console.log(err)
    })
  },

  // 拒接
  reject: function() {
    const param = {
      fromUserId: this.data.myInfo.userId,
      toUserId: this.data.chatInfo.userId,
      type: 1,
      objectName: 'RC:TxtMsg',
      content: '未接通',
      extra: '取消通话'
    }
    webSocket.sendSocketMessage({
      data: JSON.stringify(param),
      success: res => {
        console.log(2, res)
      },
      fail: err => {
        console.log(err)
      }
    })
  },

  // 主动挂断， 拒接时 回调
  handup: function(isSelf) {
    fetch.post('/converse/endConverse', { converseCode: this.data.chatInfo.converseCode }).then((data) => {
      console.log(data)
      let content = ''
      if (data.converseStatus === 5) {
        content = '已拒绝'
      } else if (data.converseStatus === 4) {
        content = '已取消'
      } else if (data.converseStatus === 3) {
        content = '已挂断'
      }
      const info = {
        content,
        fromUserId: this.data.myInfo.userId,
        msgTimestamp: new Date().toString(),
        objectName: 'RC:TxtMsg',
        toUserId: this.data.userInfo.userId,
        type: 1,
      }
      const list = this.data.list
      list.push(info)
      this.setData({ list, toView: `msg_${list.length - 1}` })
    }).catch(err => {
      // wx.showToast({
      //   title: '挂断失败',
      //   icon: 'none',
      //   duration: 2000
      // })
    })
  },

  customSocket: function() {
    const that = this
    wx.onSocketMessage(function(res) {
      const { myInfo, userInfo, chatInfo } = that.data
      const data = JSON.parse(res.data)
      console.log('接收到消息', data)
      const list = that.data.list
      // 接收的是聊天
      if (data.objectName === 'RC:TxtMsg') {
        if (chatInfo.userId === userInfo.userId || !chatInfo.userId) {
          list.push(data)
          that.setData({ list, toView: `msg_${list.length - 1}` })
        }
      }
      // 接收的是音视频邀请
      if (data.objectName === 'YH:convers') {
        wx.hideKeyboard()
        const info = JSON.parse(data.content)
        // contactsCode  联系人code
        // converseCode  视频code
        // converseType  1、语音  2、视频
        // type  2，单聊  1，群聊
        const chatInfo = {
          userId: info.friendCode,
          avator: info.friendPic,
          name: info.friendName,
          contactsCode: info.contactsCode,
          converseCode: info.converseCode,
          converseType: info.converseType,
          type: info.type,
        }
        that.setData({
          chatInfo,
          isWaiting: true,
          mettingType: info.type === '1' ? '2' : '1',
          waitingType: info.converseType === '1' ? '2' : '1',
        })
      }

      //  接收的是挂断信息
      if (data.objectName === 'YH:ConversStatus') {
        const content = JSON.parse(data.content)
        list.push({...data, content: content.content })
        that.setData({
          chatInfo: {},
          isWaiting: false,
          isMetting: false,
          waitingType: '1',
          isScaled: false,
          list,
          toView: `msg_${list.length - 1}`
        })
      }
      // 接收的是开始录制
      if (data.objectName === 'RC:CmdMsg') {
        const content = JSON.parse(data.content)
        if (content.extraType === 6) {
          that.selectComponent("#singleChat").getTranscribe(that.data.chatInfo.converseCode);
        }
      }
    })
  },
  bindChange: function(e) {
    this.setData({ message: e.detail.value })
  },
  send: function(e) {
    const message = e.detail.value
    if (!message) {
      wx.showToast({
        title: '请输入会话内容',
        icon: 'none',
        duration: 2000
      })
      return
    }
    const param = {
      fromUserId: this.data.myInfo.userId,
      toUserId: this.data.userInfo.userId,
      type: 1,
      objectName: 'RC:TxtMsg',
      content: message
    }
    this.setData({ message: '' })
    webSocket.sendSocketMessage({
      data: JSON.stringify(param),
      success: res => {
        console.log(1, res)
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  // 拒绝接听
  decline: function() {
    this.setData({ isWaiting: false })
    this.handup(true)
  },
  agreet: function() {
    wx.showLoading({
      title: '正在接听视频',
    })
    fetch.post('/converse/receiveConverse', { converseCode: this.data.chatInfo.converseCode }).then((res) => {
      wx.hideLoading()
      const { chatInfo } = this.data
      chatInfo.resourceToken = res.resourceToken
      this.setData({ isWaiting: false, isMetting: true, chatInfo })
    })
  },
  scaleAction: function() {
    this.setData({ isScaled: !this.data.isScaled })
  },
  // 挂断音视频
  destroy: function() {
    console.log('destroy')
    this.setData({ isMetting: false })
    this.handup(true)
  },
  // 对面挂断了
  streamRemoved: function() {
    console.log('streamRemoved')
    this.setData({
      chatInfo: {},
      isWaiting: false,
      isMetting: false,
      waitingType: '1',
      isScaled: false,
    })
  },
})
